package com.chihihx.launcher.ui.fragment

import android.content.res.Configuration
import com.chihihx.launcher.BaseWallPaperFragment
import com.chihihx.launcher.bean.LanguageDto
import com.chihihx.launcher.ext.getCurrentLanguageIndex
import com.chihihx.launcher.ext.getSupportedLanguages
import com.chihihx.launcher.ext.setSystemLanguageSystemWide
import com.chihihx.launcher.ext.updateAppLocale
import com.nova.android.tvlauncher.R
import com.nova.android.tvlauncher.databinding.FragmentLanguageSettingHxtvBinding
import com.nova.android.tvlauncher.databinding.ItemLanguageSettingBinding
import com.nova.android.tvlauncher.ext.clickNoRepeatWithAnim
import com.nova.android.tvlauncher.ext.scaleAnimation
import com_github_lib_base.base.BaseViewModel
import com_github_lib_base.ext.rv.addModels
import com_github_lib_base.ext.rv.setup
import com_github_lib_base.ext.stringValue

class LanguageSettingFragment :
    BaseWallPaperFragment<FragmentLanguageSettingHxtvBinding, BaseViewModel>() {

    var lastCheckedPosition = -1
    override fun initView() {

        mBind.tvTitle.text = R.string.set_language.stringValue()
        mBind.tvNextStep.text = R.string.next.stringValue()
        mBind.rvLang.setup(mutableListOf()) {
            addType(LanguageDto::class, R.layout.item_language_setting)
            onBind {
                val itemBinding = getBinding<ItemLanguageSettingBinding>()
                val item = getModel<LanguageDto>()
                itemBinding.tvLangName.text = item.name
                itemBinding.tvLangDesc.text = item.desc
                itemBinding.rbLang.isChecked = item.isChecked

                itemView.setOnFocusChangeListener { v, hasFocus ->
                    itemView.scaleAnimation(hasFocus, 1.03f)

                }

                itemView.clickNoRepeatWithAnim(shrinkScale = 0.96f) {
                    item.isChecked = true
                    if (lastCheckedPosition != -1) (models[lastCheckedPosition] as LanguageDto).isChecked =
                        false
                    adapter.notifyItemChanged(lastCheckedPosition)
                    itemBinding.rbLang.isChecked = true
                    lastCheckedPosition = modelPosition
                    setSystemLanguageSystemWide(item.locale)
                }
            }
        }

        val langList = requireContext().getSupportedLanguages()
        val index = langList.getCurrentLanguageIndex()
        langList[index].isChecked = true
        lastCheckedPosition = index

        mBind.rvLang.addModels(langList)
        mBind.rvLang.requestFocus()
        mBind.rvLang.selectedPosition = index


    }


     override fun onConfigurationChanged(newConfig: Configuration) {
         super.onConfigurationChanged(newConfig)
         newConfig.updateAppLocale()
         initView()
     }
}